﻿namespace DimensionsHelper.ExcelAddIn.Core.Sql;

/// <summary>
/// 码表的分类元素级别
/// </summary>
public class CodeMapElementLevel : CodeMapElement
{

    private readonly List<CodeMapElementLevel> _subLevels = [];
    private readonly List<CodeMapElement> _elements = [];


    public CodeMapElementLevel(CodeMapElementLevel? level, string code, string label) : 
        base(level, code, label)
    {
        level?._subLevels.Add(this);
    }


    public int Level => ContainingLevel == null ? 0 : ContainingLevel.Level + 1;


    public CodeMapElementLevel? FindLevel(int level)
    {
        if (level < 0)
        {
            return null;
        }

        if (level < Level)
        {
            return this;
        }

        CodeMapElementLevel? parent = ContainingLevel;

        while (parent != null)
        {
            if (parent.Level < level)
            {
                return parent;
            }

            parent = parent.ContainingLevel;
        }

        return parent;
    }


    /// <summary>
    /// 向当前分类级别中添加一个分类元素
    /// </summary>
    /// <param name="element">分类元素</param>
    public void AddElement(CodeMapElement element)
    {
        _elements.Add(element);
    }


    public override bool IsLevel => true;


    /// <summary>
    /// 获取当前分类级别的元素个数
    /// </summary>
    public int Count => _elements.Count;


    /// <summary>
    /// 获取当前包含的分类元素数组
    /// </summary>
    public CodeMapElement[] GetElements() => _elements.ToArray();

}
